import pinia from "@/store/index"
import { useMessageStore } from "@/store";
import { getNotReadMessage } from "@/api/message"
const messageStore = useMessageStore(pinia);

var url = "ws://localhost:8081/websocket/"
var ws;    //建立的连接
var timeout;    //心跳间隔时间
var lockReconnent = false;  //是否真正建立连接

var websocket = {
  Init: function (userId) {
    if ("WebSocket" in window) {
      ws = new WebSocket(url + userId);
    } else {
      console.log("当前浏览器不支持WebSocket");
      return;
    }
    ws.onopen = function () {
      console.log("连接成功");
      getNotReadMessage();
      heartCheck.start();
    }
    ws.onmessage = function (e) {
      //获取msg，有未读消息就显示小红点（参数变为true）
      console.log("收到消息:" + e.data);
      heartCheck.start();
      if (e.data == "您有未读消息") {
        messageStore.updateHasUnreadMessages();
      }
    }
    ws.onclose = function () {
      console.log("连接关闭");
      messageStore.updateNoneUnreadMessages();
    }
    ws.onerror = function (e) {
      console.log("发生错误");
      reconnect(userId);
    }
    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口
    window.onbeforeunload = function () {
      ws.close();
    }
  },
  //退出登录主动关闭连接
  closeWebSocket() {
    ws.close();
  },
  getWebSocket() {
    return ws;
  },
  getStatus() {
    if (ws.readyState == 0) {
      return "正在连接";
    } else if (ws.readyState == 1) {
      return "已连接";
    } else if (ws.readyState == 2) {
      return "连接正在关闭"
    } else if (ws.readyState == 3) {
      return "连接已关闭"
    }
  }
}
export default websocket;


//重连
function reconnect(uid) {
  if (lockReconnent) {
    return;
  } lockReconnent = true;
  //没连接上就一直重连，设置延迟避免请求过多
  timeout && clearTimeout(timeout);
  timeout = setTimeout(function () {
    console.log("执行断线重连")
    websocket.Init(uid);
    lockReconnent = false;
  }, 5000);
}

//心跳检验
var heartCheck = {
  timeout: 1000 * 60 * 3,  //三分钟一次心跳
  timeoutObj: null,
  serverTimeoutObj: null,
  start: function () {
    console.log("开始心跳检测");
    var self = this;
    this.timeoutObj && clearTimeout(this.timeoutObj);
    this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
    this.timeoutObj = setTimeout(function () {
      ws.send("HeartBeat");
      self.serverTimeoutObj = setTimeout(function () {
        if (ws.readyState != 1) {
          ws.close();
        }
      }, self.timeout);
    }, this.timeout)
  }
}




